package com.tangding.aspect.god.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import com.tangding.aspect.god.GodAspect;
import com.tangding.hprose.api.server.command.impl.role.GetRoles;
import com.tangding.service.entity.role.Permission;
import com.tangding.service.entity.role.Role;
import com.tangding.service.entity.role.RoleVO;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年12月23日_上午9:23:44
 *
 */
@Component
@Aspect
public class GetRolesAspect extends GodAspect {
	
	@Around(value = "execution(public * com.tangding.hprose.api.server.command.impl.role.GetRoles.exe(..))")
	public Object godPrcess(ProceedingJoinPoint pjp) throws Throwable {
		Map<String, Object> map = getUserInfo(pjp);
		String uid = map.get("uid").toString();
		
		if (!godAccount.equals(uid)) {//普通用户
			return pjp.proceed();
		}else {
			Set<Integer> roleIds = new HashSet<>();
			roleIds.add(1);//全国总代理，最高代理
			Set<Role> roles = new HashSet<>();
			Set<RoleVO> vos = new HashSet<>();
			Set<Permission> permissions = new HashSet<>();
			if (roleIds != null) {
				roleIds.forEach(roleId -> {
					Role role = roleRepository.getRole(roleId);
					if (role != null) {
						roles.add(role);
					}
				});
				
				roles.forEach(role -> {
					RoleVO vo = GetRoles.role2VO(role);
					GetRoles.getMyDownlineRoleVOs(role, vo, permissions);
					vos.add(vo);
				});
			}
			
			List<Map<String, Object>> userVos = new ArrayList<>();
			userRepository.getUserMap().values().forEach(user -> {
				if (!godAccount.equals(user.getUid())) {
					userVos.add(GetRoles.buildUserVO(user));
				}
			});
			
			Map<String, Object> result = new HashMap<>();
			result.put("permissions", permissions);
			result.put("roles", vos);
			result.put("users", userVos);
			
			return doResponseSucc(result);
		}
	}
}
